package com.example.imtoken.modules.main.wallet.manage.admin

import androidx.lifecycle.MutableLiveData
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.SPUtils
import com.example.imtoken.R
import com.example.imtoken.core.base.BaseViewModel
import com.example.imtoken.core.utils.sp.SpHelps
import com.example.imtoken.room.base.AppDataBase
import com.example.imtoken.room.schema.AccountSchema
import kotlin.concurrent.thread

class AdminManageViewModel : BaseViewModel() {

    private val defAccountLiveData = MutableLiveData<AccountSchema>()

    fun getDefAccountData(): MutableLiveData<AccountSchema> {
        return defAccountLiveData
    }

    val isSuccess = MutableLiveData(false)

    fun getDefAccount() {
        val appLogin = AppDataBase.instance.getAppLoginDao().getAppLogin()
        val account = AppDataBase.instance.getAccountDao().getDefAccount(appLogin.walletAddress)
        defAccountLiveData.value = account
    }

    fun getDefAccount(key: String?) {
        val account = AppDataBase.instance.getAccountDao().getDefAccount(key)
        defAccountLiveData.value = account
    }

    fun walletPass(pass: String): Boolean {
        val data = defAccountLiveData.value
        data?.let {
            return if (AppDataBase.instance.getAccountDao().findWalletPass(it.address, pass) > 0) {
                true
            } else {
                mErrorResId.postValue(R.string.passWordError)
                false
            }
        }
        return false
    }

    fun exitAdmin() {
        thread {
            //开始退出,清空数据库
            LogUtils.e("getAccountDao", AppDataBase.instance.getAccountDao().delete())
            LogUtils.e("getAddressBookDao", AppDataBase.instance.getAddressBookDao().delete())
            LogUtils.e("getAppLoginDao", AppDataBase.instance.getAppLoginDao().delete())
            LogUtils.e(
                "getTransactionRecordDao",
                AppDataBase.instance.getTransactionRecordDao().delete()
            )
            LogUtils.e("getWalletAddressDao", AppDataBase.instance.getWalletAddressDao().delete())
            LogUtils.e("getWalletBackUpDao", AppDataBase.instance.getWalletBackUpDao().delete())
            LogUtils.e("getWalletCheckedDao", AppDataBase.instance.getWalletCheckedDao().delete())

            SPUtils.getInstance(SpHelps.APP).put(SpHelps.APP_LOGIN, false)
            isSuccess.postValue(true)
        }
    }

}